﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace MethodWorx.Core.DomainModel
{
    /// <summary>
    /// A managed UnitOfWork storing entities and changes in a memory
    /// cache.
    /// </summary>
    public abstract class UnitOfWork : IUnitOfWork
    {
        protected Dictionary<Guid, AggregateRoot> inserted;
        protected Dictionary<Guid, AggregateRoot> deleted;
        protected Dictionary<Guid, AggregateRoot> updated;

        public UnitOfWork()
        {
            this.inserted = new Dictionary<Guid, AggregateRoot>();
            this.deleted = new Dictionary<Guid, AggregateRoot>();
            this.updated = new Dictionary<Guid, AggregateRoot>();
            this.isOpen = true;

            this.OnBegin();
        }

        private bool isOpen;

        public bool IsOpen { get { return this.isOpen; } }
        

        protected abstract void OnCommit();
        protected abstract void OnCancel();
        protected virtual void OnBegin()
        {
        }



        public void Commit()
        {
            this.OnCommit();
            this.isOpen = false;
        }

        public void Cancel()
        {
            this.OnCancel();
            this.isOpen = false;
        }

        public void RegisterChanged<T>(T entity) where T : AggregateRoot
        {
            if(!this.updated.ContainsKey(entity.Id))
                this.updated.Add(entity.Id, entity);
        }

        public void RegisterDeleted<T>(T entity) where T : AggregateRoot
        {
            if (!this.updated.ContainsKey(entity.Id))
                this.deleted.Add(entity.Id, entity);
        }

        public void RegisterAdded<T>(T entity) where T : AggregateRoot
        {
            if (!this.updated.ContainsKey(entity.Id))
                this.inserted.Add(entity.Id, entity);
        }


        public void Dispose()
        {
        }

    }
}
